package com.newly.center.business.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.newly.api.business.feign.CompanyClient;
import com.newly.center.business.service.CheckRecordService;
import com.newly.center.business.service.CompanyService;
import com.newly.center.business.service.SiteService;
import com.newly.center.business.service.VehicleService;
import com.newly.common.base.annotation.NewlyLog;
import com.newly.common.base.constants.AuthConstant;
import com.newly.common.base.constants.CodeConstant;
import com.newly.common.base.constants.MenuConstant;
import com.newly.common.base.constants.ServerUriConstant;
import com.newly.common.base.entity.R;
import com.newly.common.base.entity.auth.ICurrentTenant;
import com.newly.common.base.entity.business.Dto.CompanyDto;
import com.newly.common.base.entity.business.Po.CheckRecord;
import com.newly.common.base.entity.business.Po.Company;
import com.newly.common.base.entity.business.Po.Site;
import com.newly.common.base.entity.business.Po.Vehicle;
import com.newly.common.base.entity.business.Vo.ExcelCompany;
import com.newly.common.base.exception.NewlyException;
import com.newly.common.core.utils.ExcelUtil;
import com.newly.common.core.utils.NewlyCommonUtils;
import com.newly.common.core.utils.PageUtil;
import com.newly.common.core.utils.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @anthor sbq
 * @date 2021/10/29 10:00
 */
@RestController
@RequestMapping(ServerUriConstant.NEWLY_BUSINESS_COMPANY)
public class CompanyController implements CompanyClient {

    @Autowired
    private CompanyService companyService;

    @Autowired
    private CheckRecordService checkRecordService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private VehicleService vehicleService;

    @Autowired
    private RequestUtils requestUtils;

    @Override
    public R saveCheckRecord() {
        List<Site> sites = siteService.list();
        List<Vehicle> vehicles = vehicleService.list();

        //生成测试数据数量
        int capacity = 10;
        List<CheckRecord> checkRecords = new ArrayList<>(capacity);
        for (int i = 0; i < capacity; i++) {
            CheckRecord checkRecord = new CheckRecord();
            Site site = sites.get(RandomUtil.randomInt(sites.size()));
            Vehicle vehicle = vehicles.get(RandomUtil.randomInt(vehicles.size()));

            //标准重量
            double std = vehicle.getLoadCapacity();
            //总重量
            double total = RandomUtil.randomDouble(std, std * 2);
            //超出重量
            double over = total - std;
            DateTime createTime = RandomUtil.randomDay(-365, 365);

            checkRecord.setSiteId(site.getId())
                    .setCarNum(vehicle.getVehicleNumber())
                    .setCarType(vehicle.getVehicleType())
                    .setAxleNum(vehicle.getAxleCount())
                    .setTotalWeight(total)
                    .setStdWeight(std)
                    .setOverWeight(over)
                    .setOverRate(over / std)
                    .setResId(NewlyCommonUtils.getSnowFlakeId())
                    .setCreateTime(createTime.toString())
                    .setUpdateTime(RandomUtil.randomDate(createTime, DateField.DAY_OF_YEAR, 1, 30).toString())
                    .setIsAudit(1);
            checkRecords.add(checkRecord);
        }
        checkRecordService.saveBatch(checkRecords);
        return R.ok();
    }

    @NewlyLog(ability = MenuConstant.Ability.EXP, title = "企业", isOpen = false)
    @Override
    public void export(String name, String contactsName, Integer offset, HttpServletResponse response) {
        CompanyDto companyDto = new CompanyDto();
        companyDto.setName(name);
        companyDto.setContactsName(contactsName);
        companyDto.setOffset(offset);
        companyDto.setPageSize(1);
        ICurrentTenant currentTenant = requestUtils.getCurrentTenant();
        int totalCount = companyService.getPage(currentTenant, companyDto).getTotalCount();
        if (totalCount < 1) {
            throw new NewlyException(CodeConstant.FAILED, "无企业信息数据");
        }
        companyDto.setPageSize(totalCount);
        List<Company> list = (List<Company>) companyService.getPage(currentTenant, companyDto).getList();

        List<ExcelCompany> collect = list.stream().map(c -> {
            ExcelCompany excelCompany = BeanUtil.copyProperties(c, ExcelCompany.class, "type");
            String type;
            switch (c.getType()) {
                case 0:
                    type = "国有";
                    break;
                case 1:
                    type = "集体";
                    break;
                case 2:
                    type = "股份制";
                    break;
                case 3:
                    type = "私有";
                    break;
                case 4:
                    type = "其他";
                    break;
                default:
                    type = "";
            }
            excelCompany.setType(type);
            return excelCompany;
        }).collect(Collectors.toList());
        ExcelUtil.export(response, "企业信息表", null, collect, ExcelCompany.class);
    }

    @NewlyLog(ability = MenuConstant.Ability.QUE, title = "企业", isOpen = false)
    @Override
    public R getPage(CompanyDto companyDto) {
        ICurrentTenant currentTenant = requestUtils.getCurrentTenant();
        PageUtil page = companyService.getPage(currentTenant, companyDto);
        return R.ok(page);
    }

    @Override
    public R getDetailsById(Long id, Integer offset) {
        return R.ok(companyService.getDetailsById(id, offset));
    }

    @NewlyLog(ability = MenuConstant.Ability.UPD, title = "企业")
    @Override
    public R edit(Company company) {
        if (company.getId() == null)
            return R.fail("企业id不能为空");
        companyService.edit(company);
        return R.ok();
    }

    @NewlyLog(ability = MenuConstant.Ability.ADD, title = "企业")
    @Override
    public R save(Company company) {
        ICurrentTenant currentTenant = requestUtils.getCurrentTenant();
        companyService.save(company, currentTenant);
        return R.ok();
    }

    @NewlyLog(ability = MenuConstant.Ability.DEL, title = "企业")
    @Override
    public R delete(Long[] ids) {
        if (ids.length == 0)
            return R.fail("id不能为空");
        return companyService.delete(ids);
    }

    @Override
    public R getCompanyNames() {
        List<String> companyNames = this.companyService.getCompanyNames();
        return R.ok(companyNames);
    }

    @Override
    public R repeat(String companyName) {
        if (StringUtils.isBlank(companyName))
            return R.fail("参数企业名称不能为空！");
        return this.companyService.repeat(companyName) ? R.fail(1, "企业名称已存在") : R.ok();
    }

    @Override
    public R queryByIdsInAuth(List<String> companyIds) {
        ICurrentTenant currentTenant = requestUtils.getCurrentTenant();
        currentTenant.assertIncludeEntities(AuthConstant.AuthEntityType.COMPANY, companyIds);
        List<Company> companies = null;
        try {
            companies = companyService.getByIds(companyIds);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(e.getMessage());
        }
        return R.ok(companies);
    }
}
